package com.dkha.server.services.impl;

import com.dkha.common.enums.ApiUrlEnum;
import com.dkha.common.http.HttpUtil;
import com.dkha.common.modules.vo.camera.BayOnetCameraVO;
import com.dkha.common.modules.vo.camera.CameraInfoVO;
import com.dkha.common.modules.vo.camera.PeopleComparableVO;
import com.dkha.common.modules.vo.camera.PeopleVO;
import com.dkha.common.modules.vo.face.ApiFaceSearchReturnVO;
import com.dkha.common.modules.vo.face.ApiFaceSearchVO;
import com.dkha.common.modules.vo.face.PageVO;
import com.dkha.common.redis.RedisKeys;
import com.dkha.common.redis.RedisUtils;
import com.dkha.common.util.TimeUtil;
import com.dkha.common.util.UrlUtil;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.services.IControlBayonetMidService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version V1.0
 * @Description: TODO(please write your description)
 * All rights 成都电科慧安
 * @Title: TrackTaskImpl
 * @Package com.dkha.server.services.impl
 * @author: panhui
 * @date: 2020/1/14 12:39
 * @Copyright: 成都电科慧安
 */
@Component
@Slf4j
public class TrackTaskImpl {


    @Autowired
    private HttpUtil httpUtil;

    @Value("${api.server.prefix}")
    private String link;

    /**
     * 调用api进行人脸检测 获取到人脸的id
     * @param faceUrl
     * @param libs
     * @param minScore
     */
    public List<String> faceCheck(String faceUrl, List<String> libs, Double minScore)
    {
        List<String> faceList =new ArrayList<>();
        ApiFaceSearchVO apiFaceSearchVO = new ApiFaceSearchVO();
        apiFaceSearchVO.setUrl(faceUrl);
        apiFaceSearchVO.setLibraryIds(libs);
        apiFaceSearchVO.setMinScore(minScore);
        PageVO pageVO = new PageVO();
        pageVO.setPageSize(1);
        apiFaceSearchVO.setPageVO(pageVO);
        String json= UrlUtil.postApiData(link+ ApiUrlEnum.FACE_SEARCH_LIB.getUrl(),apiFaceSearchVO, httpUtil,gson);
//       log.error("获取数据{}",json);
        if(UtilValidate.isEmpty(json)){return faceList; }
        ApiFaceSearchReturnVO apiFaceSearchReturnVO=gson.fromJson(json,ApiFaceSearchReturnVO.class);
        if(UtilValidate.isEmpty(apiFaceSearchReturnVO) || UtilValidate.isEmpty(apiFaceSearchReturnVO.getFaces()))
        {
            return faceList;
        }
        apiFaceSearchReturnVO.getFaces().forEach(e->
        {
            if(UtilValidate.isEmpty(e.getFaceList()))
            {
                return;
            }
            e.getFaceList().forEach(a->
            {
                faceList.add(a.getFaceId());
            });
        });
        return faceList;
    }

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private Gson gson;

    @Autowired
    IControlBayonetMidService iControlBayonetMidService;
    /**
     * redis获取libid
     * @param nowTime
     * @return
     */
    public List<String> getRedisLibId(String nowTime)
    {
        List<String> list=new ArrayList<>();
        List<CameraInfoVO> cameraList = iControlBayonetMidService.selectFaceCameraBytaskInfo();
        if (!UtilValidate.isEmpty(cameraList)) {
            cameraList.forEach(e->
            {
                //去API比对
                if(redisUtils.exists(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())))
                {
                    BayOnetCameraVO bayOnetCameraVO=gson.fromJson(redisUtils.get(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())).toString(), BayOnetCameraVO.class);
                    list.add(bayOnetCameraVO.getAssociationLibraryId().toString());
                    //获取lib信息
                }
            });
        }
        return list;
    }


    /**
     * redis临时调用设置redis中属性的id
     * @param nowTime
     * @return
     */
    public void setBingDataCamerID(String nowTime)
    {


        List<CameraInfoVO> cameraList = iControlBayonetMidService.selectFaceCameraBytaskInfo();
        if (!UtilValidate.isEmpty(cameraList)) {
            cameraList.forEach(e->
            {
                //去API比对
                if(redisUtils.exists(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())))
                {
                    BayOnetCameraVO bayOnetCameraVO=gson.fromJson(redisUtils.get(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())).toString(), BayOnetCameraVO.class);
                    bayOnetCameraVO.getFeatIds().forEach(a->
                    {
                        xxx(nowTime,a);
                    });

                }
            });
        }

    }

    private void xxx(String nowTime,String faceId)
    {
        List<String> myList=getRedisCameraId(nowTime);
        myList.forEach(a->
        {
            //去API比对
            if(redisUtils.exists(RedisKeys.getCameraByFaceId(nowTime,a,faceId)))
            {
                List<PeopleVO> list=gson.fromJson(redisUtils.get(RedisKeys.getCameraByFaceId(nowTime,a,faceId)).toString(), new TypeToken<List<PeopleVO>>() {}.getType());
                if(UtilValidate.isNotEmpty(list)) {
                    list.forEach(e->
                    {
                        e.setCameraId(a);
                    });
                }
                redisUtils.set(RedisKeys.getCameraByFaceId(nowTime,a,faceId),gson.toJson(list));
            }
        });
    }

    /**
     * redis获取CameraId
     * @param nowTime
     * @return
     */
    public List<String> getRedisCameraId(String nowTime)
    {
        List<String> list=new ArrayList<>();
        List<CameraInfoVO> cameraList = iControlBayonetMidService.selectFaceCameraBytaskInfo();
        if (!UtilValidate.isEmpty(cameraList)) {
            cameraList.forEach(e->
            {
                //去API比对
                if(redisUtils.exists(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())))
                {
                    BayOnetCameraVO bayOnetCameraVO=gson.fromJson(redisUtils.get(RedisKeys.getCameraByTrack(nowTime,e.getIdFaceCamera())).toString(), BayOnetCameraVO.class);
                    list.add(bayOnetCameraVO.getCameraId().toString());
                    //获取lib信息
                }
            });
        }
        return list;
    }

    /**
     * 筛选数据
     * @return
     */
    public  Map<String,List<PeopleComparableVO>> filterPeople(List<PeopleVO> peopleVOList)
    {
        Map<String,List<PeopleComparableVO>> myMap=new HashMap<>();
        peopleVOList.forEach(e->
        {
            if(UtilValidate.isEmpty(e.getTime()))
            {
                e.setTime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(e.getTimestamp()) );
            }
            String key=e.getTime().substring(0,10);
            if(myMap.containsKey(key))
            {
                PeopleComparableVO pvo= new PeopleComparableVO();
                BeanUtils.copyProperties(e,pvo);
                myMap.get(key).add(pvo);
            }else
             {
                 List<PeopleComparableVO> lp=new ArrayList<>();
                 PeopleComparableVO pvo= new PeopleComparableVO();
                 BeanUtils.copyProperties(e,pvo);
                 lp.add(pvo);
                 myMap.put(key,lp);
             }
        });
        //对数据进行排序处理  把所有摄像头的数据整合后进行排序
        //时间和所有数据
        Map<String,List<PeopleComparableVO>> newMyMap=new HashMap<>();
        myMap.forEach((a,b)->
        {
            if(UtilValidate.isNotEmpty(b))
            {
                //按照时间戳就行排序
               Collections.sort(b);
               String lastCarmerId="";
               for(PeopleComparableVO p:b)
               {
                   //相等就不需要这个数据了
                   if(UtilValidate.isNotEmpty(p.getCameraId())) {
                       if (!p.getCameraId().equals(lastCarmerId)) {
                           if (newMyMap.containsKey(a)) {
                               newMyMap.get(a).add(p);
                           } else {
                               List<PeopleComparableVO> pList = new ArrayList<>();
                               pList.add(p);
                               newMyMap.put(a, pList);
                           }
                           lastCarmerId = p.getCameraId();
                       }
                   }
                    //筛选有用的
               }
            }
        });
        return newMyMap;
    }



    /**
     * redis获取用户信息
     * @param faceId
     * @return
     */
    public List<PeopleVO> getRedisPeopleInfo(String nowTime,String faceId)
    {
        List<PeopleVO> peopleVOList=new ArrayList<>();
        List<String> myList=getRedisCameraId(nowTime);
        myList.forEach(a->
        {
            //去API比对
            if(redisUtils.exists(RedisKeys.getCameraByFaceId(nowTime,a,faceId)))
            {
                List<PeopleVO> list=gson.fromJson(redisUtils.get(RedisKeys.getCameraByFaceId(nowTime,a,faceId)).toString(), new TypeToken<List<PeopleVO>>() {}.getType());
                if(UtilValidate.isNotEmpty(list)) {
                    peopleVOList.addAll(list);
                }
            }
        });
        return peopleVOList;
    }
}
